package com.eventos;

import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.List;

import com.google.android.maps.GeoPoint;
import com.google.android.maps.MapActivity;
import com.google.android.maps.MapController;
import com.google.android.maps.MapView;
import com.google.android.maps.Overlay;
import com.google.android.maps.OverlayItem;
import com.eventssmartphone.R;

import android.app.ProgressDialog;
import android.content.Context;
import android.graphics.drawable.Drawable;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.location.LocationProvider;
import android.os.Bundle;
import android.os.Handler;
import android.provider.Settings;
import android.util.Log;
import android.widget.Toast;

import com.eventssmartphone.JSONReaderListener;
import org.json.JSONArray;

public class ActivityRutaEvento extends MapActivity implements JSONReaderListener {
    /** Called when the activity is first created. */
	List<Overlay> mapOverlays;
	LugarOverlay overlayAmbiente;
	LugarOverlay overlayCliente;
	MapView mapa;
	private static int idEvento=0;
	ProgressDialog myProgressDialog = null;
	CoordBean coordAmbiente;
	CoordBean coordCliente;
	private RutaBean mRoad;
	
	boolean hayGPS=false;
	
	
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.ev_verruta);
        
        Bundle b = getIntent().getExtras();
		idEvento = b.getInt("Evento");
     
		
		try{
			GestorVerPosicionAmbiente.getInstance().damePosicionAmbiente(idEvento,this);
		
		}catch (Exception e){
			e.printStackTrace();
			Toast.makeText(this, "Error. Revise su conexión a Internet.", Toast.LENGTH_SHORT).show();
		}
		        
    }

	@Override
	protected boolean isRouteDisplayed() {
		// TODO Auto-generated method stub
		return false;
	}

	@Override
	public void onConnected() {
		// TODO Auto-generated method stub
		myProgressDialog = ProgressDialog.show(this, "Cargando...", "Por favor esperar...", true);
	}

	@Override
	public void onSent() {
		// TODO Auto-generated method stub
		myProgressDialog.setMessage("Procesando datos...");	
	}

	@Override
	public void onFinished(JSONArray jArray) {
		// TODO Auto-generated method stub
		
		String provider="";
		
		try{
		 provider= Settings.Secure.getString(getContentResolver(), Settings.Secure.LOCATION_PROVIDERS_ALLOWED);
		}
		catch(Exception e){
			e.printStackTrace();
		}
		
		try { 
			mapa=(MapView) findViewById(R.id.idmapa);
	        mapa.setBuiltInZoomControls(true);
	        mapOverlays = mapa.getOverlays();
	        
	        if(provider.contains("gps")){
	        	hayGPS=true;
	        }
	        else{
	        	Toast.makeText(this, "Su dispositivo movil no encuentra el GPS. Actívelo o instálelo", Toast.LENGTH_SHORT).show();
	        }
			
			//Definir Coord 1: Ambiente
	        
	        coordAmbiente=new CoordBean();
	        coordAmbiente=GestorVerPosicionAmbiente.getInstance().procesarDamePosicionAmbiente(idEvento, jArray);
			
	        int latitud=coordAmbiente.getCoordenadas().getLatitudeE6();
	        int longitud=coordAmbiente.getCoordenadas().getLongitudeE6();
	        
	        if(latitud==0 && longitud==0){
	        	Toast.makeText(this, "El evento no tiene locación geográfica", Toast.LENGTH_SHORT).show();
	        	return;
	        }
	        
	        coordAmbiente.setImagen(this.getResources().getDrawable(R.drawable.map_marker));
	        
	        overlayAmbiente = new LugarOverlay(coordAmbiente.getImagen(), this);
	        
	        mapa.getController().setCenter(coordAmbiente.getCoordenadas());
	        mapa.getController().setZoom(20);
	        
	        //Dibujar (prematuramente) Coord1: Ambiente
	        
	        OverlayItem overlayitem = new OverlayItem(coordAmbiente.getCoordenadas(), coordAmbiente.getNombre(), coordAmbiente.getDireccion());
            
	        overlayAmbiente.addOverlay(overlayitem);
	        mapOverlays.add(overlayAmbiente);
	        
	        mapOverlays.size();
	        

	        
	        
	        LocationManager locationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
	        
	        LocationListener locationListener = new LocationListener() {
	        	public void onLocationChanged(Location location) {
	        		
	        		try{
	    	        
		    	        if(hayGPS){
		    		        coordCliente=new CoordBean();
		    		        coordCliente.setCoordenadas(new GeoPoint((int)(location.getLatitude()*1e6),(int)(location.getLongitude()*1e6)));
		    		        //coordCliente.setCoordenadas(new GeoPoint((int)(-12.129586*1e6),(int)(-76.982489*1e6)));
		    		        //coordCliente.setCoordenadas(new GeoPoint((int)(0.0*1e6),(int)(0.0*1e6)));
		    		        coordCliente.setImagen(resources(R.drawable.person_maker));
		    		        
		    		        overlayCliente = new LugarOverlay(coordCliente.getImagen(), that());
		    		        //overlayCliente= new LugarOverlay(coordCliente.getImagen(),that());
		    	        }
		    	        
		    	        
		    	        
		    	        ////////////DENTRO DEL LISTENER
		    	        
		    	        //Definir Coord 2: Persona
		    	        
		    	        //coordCliente=new CoordBean();
		    	        
		    	        //coordCliente.setCoordenadas(new GeoPoint((int)(location.getLatitude()*1e6),(int)(location.getLongitude()*1e6)));
		    	        //coordCliente.setImagen(resources(R.drawable.map_marker));
		    	        
		    	        //overlayCliente= new LugarOverlay(coordCliente.getImagen(),that());
		    	        
		    	        
		    	        mapOverlays = mapa.getOverlays();
		                mapOverlays.clear();
		                
		                //RUTA
		                
		                //String url=RutaCreator.getUrl(coordAmbiente.getCoordenadas().getLatitudeE6(), coordAmbiente.getCoordenadas().getLongitudeE6(), coordCliente.getCoordenadas().getLatitudeE6(), coordCliente.getCoordenadas().getLongitudeE6());
		                
		    	        String sUrl=RutaCreator.getUrl((double)(coordAmbiente.getCoordenadas().getLatitudeE6()/1e6),(double)( coordAmbiente.getCoordenadas().getLongitudeE6()/1e6),(double)(coordCliente.getCoordenadas().getLatitudeE6()/1e6),(double)( coordCliente.getCoordenadas().getLongitudeE6()/1e6));
		                
		    	        Log.i("LA URL ES LA URL!",sUrl);
		    	        
		    	        URL url = new URL(sUrl);
		    	        
		    	        
		    	        InputStream is=url.openStream();
		    	        
		                mRoad = RutaCreator.getRoute(is);
		                
		                if(mRoad != null){
		                
		    	            //mHandler.sendEmptyMessage(0);
		    	            
		    	            RutaOverlay mapOverlay = new RutaOverlay(mRoad, mapa);
		    	            mapOverlays.add(mapOverlay);
		                
		                }else{
		                	Toast.makeText(that(), "A partir de su posición actual, no existe camino terrestre que lo lleve al evento.", Toast.LENGTH_LONG).show();
		                }
		                
		                //DIBUJAR COORD1: AMBIENTE
		                
		                OverlayItem overlayitem = new OverlayItem(coordAmbiente.getCoordenadas(), coordAmbiente.getNombre(), coordAmbiente.getDireccion());
		                
		    	        overlayAmbiente.addOverlay(overlayitem);
		    	        mapOverlays.add(overlayAmbiente);
		    	        
		    	        mapOverlays.size();
		    	        //DIBUJAR COORD2: PERSONA
		    	        
		    	        if(hayGPS){
		    		        //OverlayItem overlayitem1 = new OverlayItem(coordCliente.getCoordenadas(), "AQUI ESTA USTED",location.getProvider());
		    		        OverlayItem overlayitem1 = new OverlayItem(coordCliente.getCoordenadas(), "AQUI ESTA USTED",mRoad.ruta_pts[mRoad.ruta_pts.length - 1].getDireccion());
		    		        
		    		        overlayCliente.addOverlay(overlayitem1);
		    	            mapOverlays.add(overlayCliente);
		    	
		    	            mapOverlays.size();
		    	        }
		    	        
		                mapa.invalidate();
		            	mapa.postInvalidate();
	
		    	        
		    	        
		    	        ///////////FIN DENTRO DEL LISTENER
	        		
	    	        
	        		}catch(Exception e){
	        			Toast.makeText(that(), "Error. Revise su conexión a Internet.", Toast.LENGTH_SHORT).show();
	        			e.printStackTrace();
	        		}
	                
	        	}
	            public void onStatusChanged(String provider, int status, Bundle extras) {}
	            public void onProviderEnabled(String provider) {}
	            public void onProviderDisabled(String provider) {}
	        };
	        
	        
	        
	        String locationProvider = LocationManager.NETWORK_PROVIDER;
	        locationManager.requestLocationUpdates(locationProvider, 0, 0, locationListener);
	        Location lastKnownLocation = locationManager.getLastKnownLocation(locationProvider);
	        //locationManager.removeUpdates(locationListener);
	        
			
			
			
		} catch (Exception e){
	        e.printStackTrace();	
			Toast.makeText(this, "Error. Revise su conexión a Internet.", Toast.LENGTH_SHORT).show();
	        	
		}  
			
			myProgressDialog.dismiss();
	}
	
	private Drawable resources(int id){
		return this.getResources().getDrawable(id);
	}
	
	private ActivityRutaEvento that(){
		return this;
	}
	
	private InputStream getConnection(String url) {
        InputStream is = null;
        try {
                URLConnection conn = new URL(url).openConnection();
                is = conn.getInputStream();
        } catch (MalformedURLException e) {
                e.printStackTrace();
        } catch (IOException e) {
                e.printStackTrace();
        }
        return is;
	}
	
}
	
	
